package org.duiduo.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.duiduo.annotation.AuthLogin;
import org.duiduo.pojo.TbUser;
import org.duiduo.service.TbUserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Controller层
 *
 * @author 夜泷noga
 */
// 都不需要拦截
@AuthLogin(needLogin = false)
@Slf4j
@Controller
@RequestMapping("/login")
public class LoginController {

    @Resource(name = "TbUserServiceImpl")
    private TbUserService userService;

    @RequestMapping("/toLogin")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(HttpServletRequest request, Model model) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (StringUtils.isBlank(username)) {
            // 登录失败
            model.addAttribute("usernameMessage", "请输入用户名");
            if (StringUtils.isNotBlank(password)) model.addAttribute("password", password);
            return "login";
        }
        if (StringUtils.isBlank(password)) {
            // 登录失败
            model.addAttribute("passwordMessage", "请输入密码");
            if (StringUtils.isNotBlank(username)) model.addAttribute("username", username);
            return "login";
        }
        TbUser user = userService.getByUsernameAndPassword(username, password);
        if (user == null) {
            // 登录失败
            if (StringUtils.isNotBlank(username)) model.addAttribute("username", username);
            if (StringUtils.isNotBlank(password)) model.addAttribute("password", password);
            model.addAttribute("message", "用户名或密码不存在,请重新登录~");
            return "login";
        }
        // 登录成功
        request.getSession().setAttribute("USER", user);
        return "redirect:/user/list";
    }

    /**
     * 注销登录
     *
     * @param request
     * @return
     */
    @RequestMapping("/loginout")
    public String loginOut(HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:toLogin";
    }
}
